<!-- tabs/HardwareInfo.vue -->
<template>
    <div>
    <el-descriptions :column="2" border>
        <el-descriptions-item label="资产名">{{ asset.assetName }}</el-descriptions-item>
        <el-descriptions-item label="编码">{{ asset.assetCode }}</el-descriptions-item>
    </el-descriptions>

    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
    <el-button type="primary" @click="isEditable = !isEditable">
        {{ isEditable ? '锁定' : '编辑' }}
    </el-button>
    <el-button type="text" :disabled="!isEditable" @click="addCPU" >
        <el-icon><Plus /></el-icon>
        添加CPU
    </el-button>
    </div>  
    <el-table :data="hardware.cpu" size="small" style="margin-bottom: 10px">
        <el-table-column type="index" label="序号" width="60" :disabled="!isEditable"/>
      <el-table-column label="型号">
        <template #default="{ row }"><el-input v-model="row.model" width="180" :disabled="!isEditable"/></template>
      </el-table-column>
      <el-table-column label="核心数">
        <template #default="{ row }"><el-input v-model="row.cores" width="60" :disabled="!isEditable"/></template>
      </el-table-column>
      <el-table-column label="频率">
        <template #default="{ row }"><el-input v-model="row.frequency" width="60" :disabled="!isEditable"/></template>
      </el-table-column>
      <el-table-column label="插槽">
        <template #default="{ row }"><el-input v-model="row.slotnum" width="60" :disabled="!isEditable"/></template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }"><el-input v-model="row.status" width="60" :disabled="!isEditable"/></template>
      </el-table-column>
      <el-table-column label="操作" width="80" align="center">
        <template #default="{ $index }">
          <el-button
            type="danger"
            :icon="Minus"
            circle
            size="small"
            :disabled="!isEditable"
            @click="removeCPU($index)"
            title="删除该 CPU"
          />
        </template>
      </el-table-column>
    </el-table>
    

    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
    <el-button type="primary" @click="isEditable = !isEditable">
        {{ isEditable ? '锁定' : '编辑' }}
    </el-button>
    <el-button type="text" :disabled="!isEditable" @click="addMemory">
        <el-icon><Plus /></el-icon>
        添加内存
    </el-button>
    </div> 
    <el-table :data="hardware.memory" size="small" style="margin-bottom: 10px">
      <el-table-column label="容量">
        <template #default="{ row }"><el-input v-model="row.size" :disabled="!isEditable"/></template>
      </el-table-column>
      <el-table-column label="类型">
        <template #default="{ row }"><el-input v-model="row.type" :disabled="!isEditable"/></template>
      </el-table-column>
      <el-table-column label="速度">
        <template #default="{ row }"><el-input v-model="row.speed" :disabled="!isEditable"/></template>
      </el-table-column>
      <el-table-column label="插槽">
        <template #default="{ row }"><el-input v-model="row.slotnum" :disabled="!isEditable"/></template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }"><el-input v-model="row.status" :disabled="!isEditable"/></template>
      </el-table-column>
      <el-table-column label="操作" width="80" align="center">
        <template #default="{ $index }">
          <el-button
            type="danger"
            :icon="Minus"
            circle
            size="small"
            :disabled="!isEditable"
            @click="removeMemory($index)"
            title="删除该 Memory"
          />
        </template>
      </el-table-column>
    </el-table>

    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
    <el-button type="primary" @click="isEditable = !isEditable">
        {{ isEditable ? '锁定' : '编辑' }}
    </el-button>
    <el-button type="text" :disabled="!isEditable" @click="addDisk">
        <el-icon><Plus /></el-icon>
        添加硬盘
    </el-button>
    </div> 
    <el-table :data="hardware.disks" size="small" style="margin-bottom: 10px">
      <el-table-column label="类型">
        <template #default="{ row }"><el-input v-model="row.type" :disabled="!isEditable" /></template>
      </el-table-column>
      <el-table-column label="接口协议">
        <template #default="{ row }"><el-input v-model="row.proctocl" :disabled="!isEditable" /></template>
      </el-table-column>
      <el-table-column label="容量">
        <template #default="{ row }"><el-input v-model="row.capacity" :disabled="!isEditable" /></template>
      </el-table-column>
      <el-table-column label="速度">
        <template #default="{ row }"><el-input v-model="row.speed" :disabled="!isEditable" /></template>
      </el-table-column>
      <el-table-column label="插槽">
        <template #default="{ row }"><el-input v-model="row.slotnum" :disabled="!isEditable" /></template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }"><el-input v-model="row.status" :disabled="!isEditable" /></template>
      </el-table-column>
      <el-table-column label="操作" width="80" align="center">
        <template #default="{ $index }">
          <el-button
            type="danger"
            :icon="Minus"
            circle
            size="small"
            :disabled="!isEditable"
            @click="removeDisk($index)"
            title="删除该 Disk"
          />
        </template>
      </el-table-column>
    </el-table>

    <el-divider />

    <el-button type="success" :disabled="!isEditable" @click="submitConfig">保存配置</el-button>
  </div>
</template>

<script setup>
import { reactive, watch, onBeforeMount,toRefs,onMounted,ref} from 'vue'
import { Plus,Minus } from '@element-plus/icons-vue'
import {getAssetHardConfigInfoHandler,saveAssetHardConfigInfoHandler} from "../../../api/assets.js"
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
  asset: Object
  })
const assetHardwareMap = async(assetId)=>{
    try {
        const res = await getAssetHardConfigInfoHandler(assetId) // 等待接口返回
        
        console.log("配置获取成功:", res)
        return res
    } catch (err) {
        console.error("获取配置失败:", err)
        throw err // 如果需要让调用方知道错误
    }
}
const isEditable = ref(false)
const hardware = reactive({
  cpu: [],
  memory: [],
  disks: []
})

function initEmptyConfig() {
  hardware.cpu = [{ "model": "", "cores": "", "frequency": "","slotnum": "","status": ""}]
  hardware.memory = [{ "size": "", "type": "" ,"speed": "","slotnum": "","status": ""}]
  hardware.disks = [{ "type": "","proctocl": "","capacity": "" ,"speed": "","slotnum": "","status": ""}]
}

const loadConfig = async()=> {
  const id = props.asset?.id
  if (id) {
        // const idString=id.toString
        const res= await assetHardwareMap(id)
        console.log("assetHardwareMap:================",res.data.data)
        if (res.data.data) {
            
            const base64String = res.data.data.assetconfig
            const decodedBytes = atob(base64String);
            // 将字节串转换为 Uint8Array
            const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
            // 使用 TextDecoder 解码为字符串
            const decoder = new TextDecoder("utf-8");
            const decodedString = decoder.decode(uint8Array);
            console.log("assetconfig",decodedString)
            // 存储菜单数据到 localStorage
            // const decodedString = window.localStorage.getItem('menus');
            const hardwareinfos = JSON.parse(decodedString)
            if ( hardwareinfos.length > 0) {
                for (let i = 0; i < hardwareinfos.length; i++) {
                    const jsonString = hardwareinfos[i].configValue.replace(/'/g, '"') // 单引号替换成双引号
                    // console.log("===============202508101815 hardware.cpuaaa ==============",jsonString)
                    if (hardwareinfos[i].configKey =="cpu") {
                            hardware.cpu = JSON.parse(jsonString)
                    } else if (hardwareinfos[i].configKey =="memory") {
                        hardware.memory = JSON.parse(jsonString)
                    } else if (hardwareinfos[i].configKey == "disks") {
                        hardware.disks = JSON.parse(jsonString)
                    } else {
                        console.log("===============202508101815==============")
                    }
                }
            } else {
                await initEmptyConfig()
            }
        }
    }
}

// 监听 assetId 变化，重新加载配置
// watch(() => props.asset?.id, loadConfig, { immediate: true })

function addCPU() {
  hardware.cpu.push({ "model": "", "cores": "", "frequency": "","slotnum": "","status": ""})
}
function addMemory() {
  hardware.memory.push({ "size": "", "type": "" ,"speed": "","slotnum": "","status": ""})
}
function addDisk() {
  hardware.disks.push({ "type": "","proctocl": "","capacity": "" ,"speed": "","slotnum": "","status": ""})
}
function removeCPU(index) {
  hardware.cpu.splice(index, 1)
}
function removeMemory(index) {
  hardware.Memory.splice(index, 1)
}
function removeDisk(index) {
  hardware.Disk.splice(index, 1)
}
const submitConfig = async()=> {
    
    try {   
        const id = props.asset?.id
        if (!id) return                
        console.log("hardware======20250811",hardware)
        const data={}
        const assetId= id.toString()
        data["assetId"]=assetId
        const plainHardware = JSON.parse(JSON.stringify(hardware));
        data["assetHardConfig"]=plainHardware
        console.log("data=====20250811",data)
        const res = await saveAssetHardConfigInfoHandler(data) // 等待接口返回
        console.log("配置获取成功:", res)
        if (res.data) {
            ElMessage({
                    message: res.data.message,
                    type: 'success',
                })
            isEditable.value = false
            // await loadConfig
        } else {
            ElMessage({
                    message: res.data.message,
                    type: 'Error',
            })
        }
    } catch (err) {
        console.error("保存配置失败:", err)
        // throw err // 如果需要让调用方知道错误
    }
}
onMounted(loadConfig)
// 监听 ID 变化自动执行
watch(
  () => props.asset?.id,
  (newId, oldId) => {
    if (newId && newId !== oldId) {
      isEditable.value = false
      loadConfig()
      
    }
  }
)
</script>